#include "app_message.h"

//字符数组格式： 1 2 4 xxabcd
//json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"}
/**
 * @brief 将字符数组转换为JSON格式
 * 
 * @param msg   字符数组
 * @param len   字符数组长度
 * @return char* 返回JSON格式字符串
 */
char *app_message_charstoJSON(char *msg, int len){
    //先获取字符数组中的元素
    int conn_type = msg[0];
    int id_len = msg[1];
    int msg_len = msg[2];
    char id[id_len];
    char msg_str[msg_len];

    memcpy(id, msg + 3, id_len);
    memcpy(msg_str, msg + 3 + id_len, msg_len);
    //将id和msg中的数据转换为16进制
    char *id_hex = app_common_charsToHex(id, id_len);
    char *msg_hex = app_common_charsToHex(msg_str, msg_len);

    //拼接JSON格式字符串
    cJSON *cjson = cJSON_CreateObject();
    cJSON_AddNumberToObject(cjson, "conn_type", conn_type);
    cJSON_AddStringToObject(cjson, "id", id_hex);
    cJSON_AddStringToObject(cjson, "msg", msg_hex);
    char *json =cJSON_PrintUnformatted(cjson);
    cJSON_Delete(cjson);
    free(id_hex);
    free(msg_hex);
    return json;
}

/**
 * @brief 将JSON格式字符串转换为字符数组
 * 
 * @param json JSON格式字符串
 * @param msg  字符数组
 * @param size 字符数组容量
 * @return int 返回字符数组长度
 */
int app_message_jsonToChars(char *json, char *msg, int size){
    cJSON *cjson = cJSON_Parse(json);
    if(cjson == NULL){
        return -1;
    }
    int conn_type = cJSON_GetObjectItem(cjson, "conn_type")->valueint;
    char *id = cJSON_GetObjectItem(cjson, "id")->valuestring;
    char *msg_str = cJSON_GetObjectItem(cjson, "msg")->valuestring;

    int len = 0;
    int id_len = 0;
    int msg_len = 0;
    //将id和msg中的16进制数据转换为字符数组
    char *id_char = app_common_hexToChars(id,&id_len);
    char *msg_char = app_common_hexToChars(msg_str,&msg_len);
    len = 3 + id_len + msg_len;
    if(len > size){
        return -1;
    }
    msg[0] = conn_type;
    msg[1] = id_len;
    msg[2] = msg_len;
    memcpy(msg + 3, id_char, id_len);
    memcpy(msg + 3 + id_len, msg_char, msg_len);
    return len;
}